import React, { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import './LoginSuccess.css';

const LoginSuccess = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [countdown, setCountdown] = useState(3);

  useEffect(() => {
    const token = searchParams.get('token');
    const username = searchParams.get('username');

    if (token) {
      // 保存token到localStorage
      localStorage.setItem('token', token);
      localStorage.setItem('username', username || '用户');
      
      console.log('登录成功，token已保存:', token);
    }

    // 3秒倒计时后跳转到首页
    const timer = setInterval(() => {
      setCountdown(prev => {
        if (prev <= 1) {
          clearInterval(timer);
          navigate('/');
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(timer);
  }, [navigate, searchParams]);

  const username = searchParams.get('username') || '用户';

  return (
    <div className="login-success">
      <div className="success-card">
        <div className="success-icon">✅</div>
        <h2>登录成功！</h2>
        <p>欢迎回来，{username}！</p>
        <p className="countdown">页面将在 {countdown} 秒后自动跳转...</p>
        <button 
          className="go-home-btn"
          onClick={() => navigate('/')}
        >
          立即前往首页
        </button>
      </div>
    </div>
  );
};

export default LoginSuccess; 